package com.hilinos.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
public class JwtUtils {

    private static final String SECRET = "jsfj120JSFJ!@)";
    private static final Algorithm HMAC256 = Algorithm.HMAC256(SECRET);

    /**
     * 生成jwt认证字符串
     *
     * @param data    参数
     * @param expTime 过期时间，单位秒
     * @return
     */
    public static String generateJWT(Object data, long expTime) {
        JWTCreator.Builder builder = JWT.create().withIssuer("jsfj-admin");
        if (data != null) {
            String jsonString = EntityUtils.toJsonString(data);
            builder.withClaim("data",
                    Base64Utils.encodeToString(jsonString.getBytes(StandardCharsets.UTF_8), Base64Utils.DEFAULT));
        }
        if (expTime > 0) {
            builder.withExpiresAt(new Date(System.currentTimeMillis() + expTime * 1000));
        }
        return builder.sign(HMAC256);
    }

    /**
     * 生成jwt认证字符串
     *
     * @param jwtStr jwt认证字符串
     * @return
     */
    public static <T> T check(String jwtStr, Class<T> cls) {
        try {
            JWTVerifier verifier = JWT.require(HMAC256).build();
            DecodedJWT decodedjwt = verifier.verify(jwtStr);
            String base64Str = decodedjwt.getClaim("data").asString();

            return EntityUtils.jsonStr2Entity(new String(Base64Utils.decode(base64Str, Base64Utils.DEFAULT)), cls);
        } catch (Exception e) {
            log.info("token验证失败 token:{}", jwtStr, e);
        }
        return null;
    }

    /**
     * 生成jwt认证字符串
     *
     * @param jwtStr jwt认证字符串
     * @return
     */
    public static <T> T check(String password, String jwtStr, Class<T> cls) {
        try {
            JWTVerifier verifier = JWT.require(HMAC256).build();
            DecodedJWT decodedjwt = verifier.verify(jwtStr);
            String base64Str = decodedjwt.getClaim("data").asString();

            return EntityUtils.jsonStr2Entity(new String(Base64Utils.decode(base64Str, Base64Utils.DEFAULT)), cls);
        } catch (Exception e) {
            log.info("token验证失败 token:{}", jwtStr, e);
        }
        return null;
    }

}
